import { addCommentLikeUsingPost, delCommentLikeUsingPost } from "@/services/novel-web/commentLikeController";
import { MessageError, ToLogin } from "@/utils/commonUtils";
import { LikeFilled, LikeOutlined } from "@ant-design/icons";
import { message, Space } from "antd";
import React from "react";
import { useState } from "react";

const IconText = ({ icon, text,onclick,style,className }: { icon: React.FC; text: string; onclick?: ()=> void; style?:any;className?:any}) => (
  <Space onClick={onclick} style={style} className={className}>
    {React.createElement(icon)}
    {text}
  </Space>
);

interface LikeIconProps {
  likes: number;
  isliked: boolean;
  commentId: number;
  novelId: number;

  style?: any;
  className?: any;
};

const LikeIcon: React.FC<LikeIconProps> = ({
  likes,isliked,commentId,novelId,style,className
})=>{
  const [num,setNum] = useState(likes);
  const [flag,setFlag] = useState(isliked);

  const handleLikeClick = async (commentId,novelId) =>{
    try {
      await addCommentLikeUsingPost({
        commentId: commentId,
        novelId: novelId,
      })
      
      setFlag(true);
      setNum(num+1);
      message.success("点赞成功");

    } catch (error) {
      MessageError(error);
      ToLogin();
    }
  };

  const handleDisLikeClick = async (commentId) =>{
    try {
      await delCommentLikeUsingPost({
        commentId: commentId,
      })
      setFlag(false);
      setNum(num-1);
      message.success("已取消点赞");

    } catch (error) {
      MessageError(error);
      ToLogin();
    }
  };

  const preprocessNum = (num:number) => {
    if(num < 0) {
      num = 0;
    }
    if(flag && num == 0) // liked
    {
      return 1;
    }
    return num;
  }

  return (
    <Space style={style} className={className}
      onClick={()=>{
        flag ? handleDisLikeClick(commentId)
        : handleLikeClick(commentId,novelId);
      }}
    >
      {React.createElement(flag ? LikeFilled :LikeOutlined)}
      {preprocessNum(num)}
    </Space>

  );
};

export default LikeIcon;